package com.sgcc.epri.dcloud.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sgcc.epri.dcloud.mapper.dm.DataMaintenanceMapper;
import com.sgcc.epri.dcloud.pojo.DataMaintenance;
import com.sgcc.epri.dcloud.pojo.Result;
import com.sgcc.epri.dcloud.service.DataMaintenanceService;
import com.sgcc.epri.dcloud.util.ChoreUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class DataMaintenanceServiceImpl implements DataMaintenanceService {

    private final Logger log =  LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DataMaintenanceMapper dataMaintenanceMapper;

    @Override
    public Result selectData() {
        try{
            //查询所有的数据
            QueryWrapper<DataMaintenance> dmqw = new QueryWrapper<>();
            dmqw.orderByAsc("sort");
            List<DataMaintenance> allList= dataMaintenanceMapper.selectList(dmqw);
            //创建一个list集合，用于存放根节点
            List<DataMaintenance> parent=new ArrayList<>();
            for(DataMaintenance person:allList){
                //如果parentId为0，则代表是根节点，存入到集合中
                if(person.getParentId().equals("0")){
                    parent.add(person);
                }
            }
            //查找根节点下的子类，因为根节点的id就是 子节点的parentId;
            for(DataMaintenance person:parent){
                List<DataMaintenance> children=getChild(person.getId()+"",allList);
                person.setChildren(children);
            }
            return Result.success(parent);
        }catch (Exception e){
            e.printStackTrace();
            log.error("查询维护信息失败!");
            return Result.error("查询维护信息失败!");
        }
    }

    @Override
    public Result insertData(DataMaintenance dataMaintenance) {
        try{
            if (ChoreUtil.isAlpha(dataMaintenance.getNrCode()) &&
                    ChoreUtil.isAlpha(dataMaintenance.getTitle()) &&
                    ChoreUtil.isAlpha(dataMaintenance.getDkyCode())) {
                dataMaintenance.setSort(NumberUtil.generateRandomNumber(1, 99999, 1)[0]+"");
                dataMaintenanceMapper.insert(dataMaintenance);
                return Result.success("插入维护信息成功!");
            }
            if(ChoreUtil.isAlpha(dataMaintenance.getNrCode())) return Result.success("nr_code 不得为空！");
            if (dataMaintenance.getLevel().equals("1")) {
                int i = dataMaintenanceMapper.queryObjectNameByCount(dataMaintenance.getTitle());
                if (i == 0) {
                    return Result.success("请输入正确的对象名称!");
                }
                QueryWrapper<DataMaintenance> dmqw = new QueryWrapper<>();
                dmqw.eq("dky_code", dataMaintenance.getDkyCode());
                dmqw.eq("nr_code", dataMaintenance.getNrCode());
                List<DataMaintenance> dataMaintenances = dataMaintenanceMapper.selectList(dmqw);
                if (dataMaintenances.size() > 0) {
                    return Result.success("不得录入重复的映射关系！");
                }
            }

            dataMaintenance.setSort(NumberUtil.generateRandomNumber(1, 99999, 1)[0]+"");
            dataMaintenanceMapper.insert(dataMaintenance);
            return Result.success("插入维护信息成功!");
        }catch (Exception e){
            e.printStackTrace();
            log.error("插入维护信息失败!");
            return Result.error("插入维护信息失败!");
        }
    }

    @Override
    public Result updateData(DataMaintenance dataMaintenance) {
        try{
            dataMaintenanceMapper.updateById(dataMaintenance);
            return Result.success("修改维护信息成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error("修改维护信息失败");
            return Result.error("修改维护信息失败");
        }
    }

    @Override
    public Result deleteData(String id) {
        try{
            QueryWrapper<DataMaintenance> queryWrapper =new QueryWrapper<>();
            queryWrapper.eq("parent_id",id);
            //首先查出当前节点是否存在子节点，如果存在，则遍历删除子节点
            List<DataMaintenance> personList=dataMaintenanceMapper.selectList(queryWrapper);
            //递归查出所有的子节点，personList为null是递归结束条件，如果当前子节点还存在子节点，则再次执行当前方法，只到找到不存子节点的那项结束
            if(personList!=null&&personList.size()>0){
                for (DataMaintenance treeNode:personList){
                    deleteData(treeNode.getId()+"");
                }
            }
            dataMaintenanceMapper.deleteById(id);
            return Result.success("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error("删除失败！"+e);
            return Result.error("删除失败");
        }
    }

    @Transactional
    @Override
    public Result upOrDown(String hostId, String rmId) {
        try{

            CompletableFuture<DataMaintenance> hostFuture = querySortById(hostId);
            CompletableFuture<DataMaintenance> rmFuture = querySortById(rmId);

            // 等待sql执行
            CompletableFuture.allOf(hostFuture, rmFuture).join();

            QueryWrapper<DataMaintenance> dmqwHost = new QueryWrapper<>();
            dmqwHost.eq("id", hostId);
            DataMaintenance hostTableHead = new DataMaintenance();
            hostTableHead.setSort(rmFuture.get().getSort());
            dataMaintenanceMapper.update(hostTableHead, dmqwHost);

            QueryWrapper<DataMaintenance> dmqwRm = new QueryWrapper<>();
            dmqwRm.eq("id", rmId);
            DataMaintenance rmTableHead = new DataMaintenance();
            rmTableHead.setSort(hostFuture.get().getSort());
            dataMaintenanceMapper.update(rmTableHead, dmqwRm);

            return Result.success("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error("修改失败"+e);
            return Result.error("修改失败");
        }
    }

    @Async("threadPoolTaskExecutor")
    public CompletableFuture<DataMaintenance> querySortById(String id){
        try{
            QueryWrapper<DataMaintenance> oqw = new QueryWrapper<>();
            oqw.eq("id",id);
            return CompletableFuture.completedFuture(dataMaintenanceMapper.selectOne(oqw));
        }catch (Exception e){
            e.printStackTrace();
            log.error("Error executing SQL query: {}", e);
            return null;
        }
    }

    //查找子节点的方法
    private List<DataMaintenance> getChild(String id, List<DataMaintenance> allList) {
        //存放子节点的集合
        List<DataMaintenance> children=new ArrayList<>();
        for (DataMaintenance person:allList){
            //如果根节点的id 等于集合内parentid，说明是根节点的子节点
            if(person.getParentId().equals(id)){
                //存入子节点集合
                children.add(person);
            }
        }

        for (DataMaintenance person:children){
            //递归调用，如果子节点存在根节点，则再次调用，往后依次推
            List<DataMaintenance> personChildren= getChild(person.getId()+"",allList);
            person.setChildren(personChildren);
        }
        //递归结束条件，如果子节点不存在子节点，则递归结束
        if(children==null){
            return null;
        }
        return children;
    }
}
